package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author wfyn
 * @date 2023/10/8
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    OrderMapper orderMapper;


    /**
     * 取消订单超时处理方法
     * 原理：如果已超过15分钟则将订单状态修改为已取消。
     */
    @Scheduled(cron = "0 0/2 * * * ?")
    public void processPaymentTimeOut() {

        LocalDateTime orderTime = LocalDateTime.now().minusMinutes(15);

        List<Orders> orderList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, orderTime);

        if (orderList != null && !orderList.isEmpty()) {
            for (Orders orders : orderList) {
                log.info("[{}] 订单超时 -> 将订单状态修改为已取消", orders.getNumber());
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("订单超时，自动取消");
                orderMapper.update(orders);
            }

        }
    }


    /**
     * 处理一直处于 派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    //@Scheduled(cron = "0/5 * * * * ?")
    public void processDeliveryOrder() {
        log.info("定时处理处于派送中的订单：{}",LocalDateTime.now());
        List<Orders> orderList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().minusHours(60));
        if (orderList != null && !orderList.isEmpty()) {
            for (Orders orders: orderList) {
                log.info("[{}] 订单超时 -> 将订单状态修改为已完成", orders.getNumber());
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }



    }
}

